//
//  FtLocationManager.m
//  Feast
//
//  Created by 胡光健 on 2017/8/26.
//  Copyright © 2017年 mac. All rights reserved.
//

#import "FtLocationManager.h"
#import <MapKit/MapKit.h>
#import "FMDB.h"

#define TZLocationModelFilePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"locationModel.plist"]

@interface FtLocationManager ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
/// 定位成功的回调block
@property (nonatomic, copy) void (^successBlock)(CLLocation *location,CLLocation *oldLocation);
/// 编码成功的回调block
@property (nonatomic, copy) void (^geocodeBlock)(NSArray *geocodeArray);
/// 定位失败的回调block
@property (nonatomic, copy) void (^failureBlock)(NSError *error);
@end

@implementation FtLocationManager

static FMDatabase *_db;

+ (void)initialize {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"city.db" ofType:nil];
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
}

+ (instancetype)manager {
    static FtLocationManager *manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
        manager.locationManager = [[CLLocationManager alloc] init];
        manager.locationManager.delegate = manager;
        [manager.locationManager requestWhenInUseAuthorization];
    });
    return manager;
}

- (void)startLocation {
    [self startLocationWithSuccessBlock:nil failureBlock:nil geocoderBlock:nil];
}

- (void)startLocationWithSuccessBlock:(void (^)(CLLocation *location,CLLocation *oldLocation))successBlock failureBlock:(void (^)(NSError *error))failureBlock {
    [self startLocationWithSuccessBlock:successBlock failureBlock:failureBlock geocoderBlock:nil];
}

- (void)startLocationWithGeocoderBlock:(void (^)(NSArray *geocoderArray))geocoderBlock {
    [self startLocationWithSuccessBlock:nil failureBlock:nil geocoderBlock:geocoderBlock];
}

- (void)startLocationWithSuccessBlock:(void (^)(CLLocation *location,CLLocation *oldLocation))successBlock failureBlock:(void (^)(NSError *error))failureBlock geocoderBlock:(void (^)(NSArray *geocoderArray))geocoderBlock {
    [self.locationManager startUpdatingLocation];
    _successBlock = successBlock;
    _geocodeBlock = geocoderBlock;
    _failureBlock = failureBlock;
}

#pragma mark - CLLocationManagerDelegate

/// 地理位置发生改变时触发
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    [manager stopUpdatingLocation];
    
    [mUserDefaults setObject:@(newLocation.coordinate.latitude) forKey:@"lat"];
    [mUserDefaults setObject:@(fabs(newLocation.coordinate.longitude)) forKey:@"lng"];
    [mUserDefaults synchronize];
    
    if (_successBlock) {
        _successBlock(newLocation,oldLocation);
    }
    
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *array, NSError *error) {
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            NSString *whereStr = placemark.locality;
            whereStr = [whereStr stringByReplacingOccurrencesOfString:@"市" withString:@""];
            if (whereStr == nil || [whereStr isEqualToString:@""] || whereStr.length < 1) {
                whereStr = @"上海";
            }
            [mUserDefaults setObject:whereStr forKey:@"userCity"];
            [mUserDefaults synchronize];
//            NSLog(@"当前定位城市：%@",whereStr);
            if (_geocodeBlock) {
                _geocodeBlock(array);
            }
        }
    }];
}

/// 定位失败回调方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    NSLog(@"定位失败, 错误: %@",error);
    switch([error code]) {
        case kCLErrorDenied: { // 用户禁止了定位权限
            NSString *message = [NSString stringWithFormat:@"请到设置->隐私->定位服务中开启[%@]定位服务以获取您的小区，以便我们给您提供更精准的服务", [CommonTools appDisplayName]];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"定位服务已关闭" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"设置", nil];
            [alert.rac_buttonClickedSignal subscribeNext:^(NSNumber *x) {
                if (x.integerValue == 1) {
                    // 去设置页面
                    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
                }
            }];
            [alert show];
        } break;
        default: break;
    }
    if (_failureBlock) {
        _failureBlock(error);
    }
}

/// 获取当前的位置模型
+ (TZLocationModel *)currentLocationModel {
    TZLocationModel *model;
    NSDictionary *location = [NSKeyedUnarchiver unarchiveObjectWithFile:TZLocationModelFilePath];
    model = [TZLocationModel mj_objectWithKeyValues:location];
    if (!model) {
        model = [[TZLocationModel alloc] init];
        NSString *locaName = [mUserDefaults objectForKey:@"userCity"];
        if (locaName.length) {
            model.name = locaName;
        } else {
            model.name = @"定位中";
        }
    }
    return model;
}

/// 存储当前的位置模型
+ (void)setLocationModel:(TZLocationModel *)model {
    model.provinceId = [self getProvinceIdWithName:model.name];
    NSDictionary *location = [model mj_JSONObject];
    [NSKeyedArchiver archiveRootObject:location toFile:TZLocationModelFilePath];
}

/// 从数据库中搜索pid = 0 且 name像provinceName的省份
+ (NSString *)getProvinceIdWithName:(NSString *)provinceName {
    NSString *provinceId;
    NSString *sqlURL = [NSString stringWithFormat:@"SELECT * FROM city WHERE name LIKE '%@' AND pid = 0;",provinceName];
    FMResultSet *set = [_db executeQuery:sqlURL];
    
    NSMutableArray *models = [NSMutableArray array];
    if (set.next) {
        NSDictionary *dict = set.resultDictionary;
        provinceId = dict[@"cid"];
        [models addObject:dict];
    } else {
        provinceId = @"9";
        //        [[UIViewController currentViewController] showErrorHUDWithError:@"APP不支持英文语言,请在设置语言中选择简体中文"];
    }
    return provinceId;
}

/// 获取该城市模型下的 子区域模型列表
+ (NSArray *)getSubCitysWithModel:(TZCityModel *)cityModel {
    return [self getSubCitysWithPid:cityModel.cid];
}

+ (NSArray *)getSubCitysWithPid:(NSString *)pid {
    NSString *sqlURL = [NSString stringWithFormat:@"SELECT * FROM city WHERE pid = %zd;",pid.integerValue];
    
    FMResultSet *set = [_db executeQuery:sqlURL];
    NSMutableArray *models = [NSMutableArray array];
    while (set.next) {
        TZCityModel *cityModel = [TZCityModel mj_objectWithKeyValues:set.resultDictionary];
        if (![cityModel.name containsString:@"其他"] && ![cityModel.name containsString:@"长株潭"]) {
            [models addObject:cityModel];
        }
    }
    return models;
}

@end


@implementation TZLocationModel

@end


@implementation TZCityModel

@end

